<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Admin\Controller;

/**
 * 模型数据管理控制器
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
class ProductOrderController extends ThinkController{
	/**
     * 显示指定模型列表数据
     * @param  String $model 模型标识
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
	public function lists($model = null, $p = 0){
		$model || $this->error('模型名标识必须！');
		$page = intval($p);
        $page = $page ? $page : 1; //默认显示第一页数据

        //获取模型信息
        $model = M('Model')->getByName($model);
        $model || $this->error('模型不存在！');

        $map  = array();

        $begin_time = $_GET['begin_time']?strtotime($_GET['begin_time']):000000000;
        $end_time = $_GET['end_time']?strtotime($_GET['end_time'])+3600*24:9999999999;
        $status = strlen($_GET['status'])>0?$_GET['status']:null;
        $attribution = $_GET['attribute_select']?$_GET['attribute_select']:null;

        //filter放进默认变量 以供前台显示
        $default_filter['begin_time'] = $_GET['begin_time']?$_GET['begin_time']:null;
        $default_filter['end_time'] = $_GET['end_time']?$_GET['end_time']:null;
        $default_filter['status'] = $_GET['status']?$_GET['status']:null;
        $default_filter['attribute_select'] = $_GET['attribute_select']?$_GET['attribute_select']:null;

        $status_array = array();
        if(strlen($status)>0){
          $status_array = explode(',',$status);
          $map['status'] = array('in',$status_array);
        }

        /* 查询所有记录 */
        $name = parse_name(get_table_name($model['id']), true);
        // 有属性筛选项
        if($attribution){
          $total = M($name)
          ->field('product_order.*')
          ->where("product_order.create_time >= ".$begin_time." and product_order.create_time < ".$end_time)
          ->where($map)
          ->join('product_to_cart on (product_to_cart.product_order_id = product_order.id and product_to_cart.attribution_id = '.$attribution.')')
          ->select();
        }else{//没有属性筛选
          $total = M($name)
          ->field('product_order.*')
          ->where("create_time >= ".$begin_time." and create_time < ".$end_time)
          ->where($map)
          ->select();
        }
        
        $total_amount  = 0;
        $total_price = 0;

        //计算订单数跟商品件数
        foreach ($total as $total_key => $total_value) {
          # code...
          // 总数量
          $total[$total_key]['total_amount'] = 0;
          // 总价
          $total[$total_key]['total_price'] = 0;

          $ids = explode(',',$total_value['cart_ids']);
          foreach ($ids as $key => $value) {
            # code...
            $cart = M('cart')->find($value);
            if($attribution){//有属性选项
              if($cart['attribution_id']==$attribution){
                $total[$total_key]['total_amount'] = $total[$total_key]['total_amount'] + $cart['quantity'];
                $total[$total_key]['total_price'] = $total[$total_key]['total_price'] + ($cart['activity_price']>0?$cart['activity_price']*$cart['quantity']:$cart['price']*$cart['quantity']);
              }
            }else{
              $total[$total_key]['total_amount'] = $total[$total_key]['total_amount'] + $cart['quantity'];
              $total[$total_key]['total_price'] = $total[$total_key]['total_price'] + ($cart['activity_price']>0?$cart['activity_price']*$cart['quantity']:$cart['price']*$cart['quantity']);
            }
          }
          $total_amount = $total_amount + $total[$total_key]['total_amount'];
          $total_price = $total_price + $total[$total_key]['total_price'];
        }

        $filter_count['total_price'] = $total_price;
        $filter_count['total_amount'] = $total_amount;

        //解析列表规则
        $fields = array();
        $grids  = preg_split('/[;\r\n]+/s', trim($model['list_grid']));
        foreach ($grids as &$value) {
        	if(trim($value) === ''){
        		continue;
        	}
            // 字段:标题:链接
        	$val      = explode(':', $value);
            // 支持多个字段显示
        	$field   = explode(',', $val[0]);
        	$value    = array('field' => $field, 'title' => $val[1]);
        	if(isset($val[2])){
                // 链接信息
        		$value['href']	=	$val[2];
                // 搜索链接信息中的字段信息
        		preg_replace_callback('/\[([a-z_]+)\]/', function($match) use(&$fields){$fields[]=$match[1];}, $value['href']);
        	}
        	if(strpos($val[1],'|')){
                // 显示格式定义
        		list($value['title'],$value['format'])    =   explode('|',$val[1]);
        	}
        	foreach($field as $val){
        		$array	=	explode('|',$val);
        		$fields[] = $array[0];
        	}
        }
        // 过滤重复字段信息
        $fields =   array_unique($fields);
        
        $row    = empty($model['list_row']) ? 10 : $model['list_row'];

        //读取模型数据列表
        if($model['extend']){
        	$name   = get_table_name($model['id']);
        	$parent = get_table_name($model['extend']);
        	$fix    = C("DB_PREFIX");

        	$key = array_search('id', $fields);
        	if(false === $key){
        		array_push($fields, "{$fix}{$parent}.id as id");
        	} else {
        		$fields[$key] = "{$fix}{$parent}.id as id";
        	}

        	/* 查询记录数 */
        	$count = M($parent)->join("INNER JOIN {$fix}{$name} ON {$fix}{$parent}.id = {$fix}{$name}.id")->where($map)->count();

            // 查询数据
        	$data   = M($parent)
        	->join("INNER JOIN {$fix}{$name} ON {$fix}{$parent}.id = {$fix}{$name}.id")
        	/* 查询指定字段，不指定则查询所有字段 */
        	->field(empty($fields) ? true : $fields)
                // 查询条件
        	->where($map)
        	/* 默认通过id逆序排列 */
        	->order("{$fix}{$parent}.id DESC")
        	/* 数据分页 */
        	->page($page, $row)
        	/* 执行查询 */
        	->select();

        } else {
        	if($model['need_pk']){
        		in_array('id', $fields) || array_push($fields, 'id');
        	}
        	$name = parse_name(get_table_name($model['id']), true);
          if($attribution){
            $data = M($name)
            /* 查询指定字段，不指定则查询所有字段 */
            // ->field(empty($fields) ? true : $fields)
            ->field('product_order.*')
                  // 查询条件
            ->where("product_order.create_time >= ".$begin_time." and product_order.create_time < ".$end_time)
            ->where($map)
            ->join('product_to_cart on (product_to_cart.product_order_id = product_order.id and product_to_cart.attribution_id = '.$attribution.')')
            /* 默认通过id逆序排列 */
            ->order($model['need_pk']?'id DESC':'')
            /* 数据分页 */
            ->page($page, $row)
            /* 执行查询 */
            ->select();

            /* 查询记录总数 */
            $count = M($name)
            ->where("product_order.create_time >= ".$begin_time." and product_order.create_time < ".$end_time)
            ->field('product_order.*')
            ->join('product_to_cart on (product_to_cart.product_order_id = product_order.id and product_to_cart.attribution_id = '.$attribution.')')
            ->where($map)
            ->count();
          }else{
            $data = M($name)
            /* 查询指定字段，不指定则查询所有字段 */
            // ->field(empty($fields) ? true : $fields)
            ->field('product_order.*')
                  // 查询条件
            ->where("create_time >= ".$begin_time." and create_time < ".$end_time)
            ->where($map)
            /* 默认通过id逆序排列 */
            ->order($model['need_pk']?'id DESC':'')
            /* 数据分页 */
            ->page($page, $row)
            /* 执行查询 */
            ->select();

            /* 查询记录总数 */
            $count = M($name)
            ->where("create_time >= ".$begin_time." and create_time < ".$end_time)
            ->field('product_order.*')
            ->where($map)
            ->count();
          }
        	
        }

        //分页
        if($count > $row){
        	$page = new \Think\Page($count, $row);
        	$page->setConfig('theme','%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
        	$this->assign('_page', $page->show());
        }

        $data   =   $this->parseDocumentList($data,$model['id']);
        //获取所有属性，用于筛选
        $attributes = M('product_attribution')
        ->field('product_attribution.id,product_attribution.name as attribution_name,product.name as product_name')
        ->where(array('product_attribution.is_deleted'=>0))
        ->join('product on product.id = product_attribution.product_id')
        ->select();

        $this->assign('model', $model);
        $this->assign('list_grids', $grids);
        $this->assign('list_data', $data);
        $this->assign('filter_count', $filter_count);
        $this->assign('count', $count);
        $this->assign('default_filter', $default_filter);
        $this->assign('attributes', $attributes);
        $this->meta_title = $model['title'].'列表';
        $this->display($model['template_list']);
      }

      public function del($model = null, $ids=null){
      	$model = M('Model')->find($model);
      	$model || $this->error('模型不存在！');

      	$ids = array_unique((array)I('ids',0));

      	if ( empty($ids) ) {
      		$this->error('请选择要操作的数据!');
      	}

      	$Model = M(get_table_name($model['id']));
      	$map = array('id' => array('in', $ids) );
      	if($Model->where($map)->delete()){
      		$this->success('删除成功');
      	} else {
      		$this->error('删除失败！');
      	}
      }

    /**
     * 设置一条或者多条数据的状态
     * @author huajie <banhuajie@163.com>
     */
    public function setStatus($model='Document'){
    	return parent::setStatus($model);
    }
    
    public function edit($model = null, $id = 0){
        //获取模型信息
      $model = M('Model')->find($model);
      $model || $this->error('模型不存在！');

      if(IS_POST){
        $Model  =   D(parse_name(get_table_name($model['id']),1));
            // 获取模型的字段信息
        $Model  =   $this->checkAttr($Model,$model['id']);
        if($Model->create() && $Model->save()){
          $this->success('保存'.$model['title'].'成功！', U('lists?model='.$model['name']));
        } else {
          $this->error($Model->getError());
        }
      } else {
        $fields     = get_model_attribute($model['id']); 

        //获取数据
        $data = M(get_table_name($model['id']))->find($id);
        $data || $this->error('数据不存在！');

        $valArr = M('product_attribution')->where(array('product_id'=>$data['id'],'is_deleted'=>'0'))->select();
        $value = json_encode($valArr,true);

        $re_visitor = M('visitor')->where(array('id'=>$data['visitor_id']))->find();
        $re_address = M('address')
        ->field('address.*,r1.name as province_name,r2.name as city_name,r3.name as district_name')
        ->where(array('address.id'=>$data['address_id']))
        ->join('region r1 on r1.id = address.province')
        ->join('region r2 on r2.id = address.city')
        ->join('region r3 on r3.id = address.district')
        ->find();
        $re_payment = M('payment')->where(array('id'=>$data['payment_num']))->find();
        if(strlen($data['cart_ids'])>0){
          $ids = explode(',',$data['cart_ids']);
          $products = array();
          foreach ($ids as $key => $value) {
            $product = M('cart')
            ->field('cart.*,picture.path as product_cover,product.name as product_name,product.name_en as product_name_en,product_attribution.name as attr_name')
            ->where(array('cart.id'=>$value))
            ->join('product on product.id = cart.product_id')
            ->join('product_attribution on product_attribution.id = cart.attribution_id')
            ->join('picture on picture.id = product.cover','left')
            ->find();
            $product['product_cover'] = __ROOT__.$product['product_cover'];
            array_push($products,$product);
          }
        }

        $data['create_time'] = date('Y-m-d H:i',$data['create_time']);
        $data['visitor_name'] = $re_visitor['name'];
        $data['visitor_phone'] = $re_visitor['phone'];
        $data['address'] = $re_address['province_name'].$re_address['city_name'].$re_address['district_name'].$re_address['area'];
        $data['receive_name'] = $re_address['name'];
        $data['receive_phone'] = $re_address['phone'];
        $data['pay_time'] = $re_payment['create_time']?date('Y-m-d H:i',$re_payment['create_time']):null;
        $data['products'] = $products;

      // var_dump($data);

        $this->assign('model', $model);
        $this->assign('fields', $fields);
        $this->assign('data', $data);
        $this->meta_title = '编辑'.$model['title'];
        $this->display($model['template_edit']?$model['template_edit']:'');

      }
    }

    public function add($model = null){
        //获取模型信息
      $model = M('Model')->where(array('status' => 1))->find($model);
      $model || $this->error('模型不存在！');
      if(IS_POST){
        $_POST['district'] = $_POST['province'].','.$_POST['city'].','.$_POST['district'];
        $Model  =   D(parse_name(get_table_name($model['id']),1));
            // 获取模型的字段信息
        $Model  =   $this->checkAttr($Model,$model['id']);
        if($Model->create() && $Model->add()){
          $this->success('添加'.$model['title'].'成功！', U('lists?model='.$model['name']));
        } else {
          $this->error($Model->getError());
        }
      } else {

        $fields = get_model_attribute($model['id']);

        $this->assign('model', $model);
        $this->assign('fields', $fields);
        $this->meta_title = '新增'.$model['title'];
        $this->display($model['template_add']?$model['template_add']:'');
      }
    }

    public function data_export(){//后台导出
      $begin_time = $_POST['begin_time']?strtotime($_POST['begin_time']):000000000;
      $end_time = $_POST['end_time']?strtotime($_POST['end_time'])+3600*24:9999999999;
      $status = strlen($_POST['status'])>0?$_POST['status']:null;
      $attribution = $_POST['attribute_select']?$_POST['attribute_select']:null;

      $where = "product_order.create_time >= $begin_time and product_order.create_time < $end_time";
      if(strlen($_POST['status'])>0){
        $where = $where." and (";
        $status = explode(',',$_POST['status']);
        $len = count($status);
        foreach ($status as $key => $value) {
          if($key==$len-1){
            $where = $where." product_order.status = '".$value."')";
          }else{
            $where = $where." product_order.status = '".$value."' or";
          }
        }
      }

      $map = array();
      if($attribution){
        $map['product_to_cart.attribution_id'] = $attribution;
      }

      $orders = M('product_to_cart')
      ->field('product_order.*,visitor.name as visitor_name,address.area,address.name as receive_name,address.phone as receive_phone,r1.name as province_name,r2.name as city_name,r3.name as district_name,product_to_cart.product_id,product_to_cart.quantity,product_to_cart.cart_id')
      ->where($where)
      ->where($map)
      ->join('product_order on product_order.id = product_to_cart.product_order_id')
      ->join('visitor on visitor.id = product_order.visitor_id','left')
      ->join('address on address.id = product_order.address_id','left')
      ->join('region r1 on r1.id = address.province','left')
      ->join('region r2 on r2.id = address.city','left')
      ->join('region r3 on r3.id = address.district','left')
      ->select();

      foreach ($orders as $order_key => $order) {
        if($order['cart_id']){
          $product = M('cart')
          ->field('cart.*,picture.path as product_cover,product.name as product_name,product.name_en as product_name_en,product_attribution.name as attr_name')
          ->where(array('cart.id'=>$order['cart_id']))
          ->join('product on product.id = cart.product_id')
          ->join('product_attribution on product_attribution.id = cart.attribution_id')
          ->join('picture on picture.id = product.cover','left')
          ->find();

          $orders[$order_key]['products_str'] = $products_str;
          $orders[$order_key]['price'] = $product['price'];
          $orders[$order_key]['activity_price'] = $product['activity_price'];
          $orders[$order_key]['product_name'] = $product['product_name'];
          $orders[$order_key]['attr_name'] = $product['attr_name'];
          $orders[$order_key]['total'] = $product['activity_price']>0?$product['activity_price']*$product['quantity']:$product['price']*$product['quantity'];
          # 支付方式
          if($order['payment']=='1'){
            $orders[$order_key]['payment'] = '微信支付';
          }else if($order['payment']=='2'){
            $orders[$order_key]['payment'] = '支付宝支付';
          }else{
            $orders[$order_key]['payment'] = '现金支付';
          }
          # 状态
          switch($order['status']){
            case '0': $orders[$order_key]['status'] = '未支付';break;
            case '1': $orders[$order_key]['status'] = '已支付';break;
            case '2': $orders[$order_key]['status'] = '已发货';break;
            case '3': $orders[$order_key]['status'] = '已完成';break;
            case '4': $orders[$order_key]['status'] = '库存不足，交易关闭';break;
            case '5': $orders[$order_key]['status'] = '其他原因，交易关闭';break;
            default: $orders[$order_key]['status'] = '无';;
          }
          // 时间
          $orders[$order_key]['create_time'] = date('Y-m-d H:i:s',$orders[$order_key]['create_time']);
          //地址拼接
          $orders[$order_key]['receive_address'] = $order['province_name'].$order['city_name'].$order['district_name'].$order['area']." ".$order['receive_name'].$order['receive_phone'];
          //总金额
          $orders[$order_key]['total'] = floatval($orders[$order_key]['total']);
        }
      }

      $excel = new \Think\Excel();
      // $image = array('avatar'=>'image');
      $excel_title = array('订单编号','下单用户','下单时间','商品名称','商品规格','购买数量','单价','活动价','总金额','状态','收货地址','快递公司','快递单号','支付方式');
      $row_keys = array('order_num','visitor_name','create_time','product_name','attr_name','quantity','price','activity_price','total','status','receive_address','express_co','express_num','payment');
      $headers_types['total'] = 'number';
      $excel->prepareDownloadExcel($orders,$excel_title,$row_keys,'商品订单',$headers_types);
    }

    public function sendProduct(){
      $product_order_id = I('get.id');
      $express_num = I('get.express_num')?I('get.express_num'):null;
      $express_co = I('get.express_co')?I('get.express_co'):null;
      if(!$product_order_id){
        $this->error('参数错误，发货失败');
      }
      $re=M('product_order')->where(array('id'=>$product_order_id))->save(array('status'=>2,'express_num'=>$express_num,'express_co'=>$express_co));
      if($re){
        $this->success('发货成功！', U('lists?model=product_order'));
      }
    }
  }